import os
import re

import redis


def get_measure_table_or_view(cube, measure, win_conn, path):
    '''
    获取量值对应视图或表
    :param cube: 多维数据集对象
    :param measure: 多维数据集量值对象
    :param win_conn: 远程主机连接
    :param path: 远程文件路径
    :return:
    '''
    redis_conn = redis.Redis(host='127.0.0.1', port=6379, db=12)
    redis_key = "{}-{}-{}-cub".format(win_conn.host, path, cube.CUBE_NAME)
    if not redis_conn.get(redis_key):
        drive_letter = path.split(':')[0]
        cube_dirs = win_conn.connect.run_cmd('{0}: & cd {1} & dir /b *.cub'.format(drive_letter, path))
        cube_dirs = cube_dirs.std_out.decode().split('\r\n')
        cube_dir_name = ''
        for cube_dir in cube_dirs:
            if cube.CUBE_NAME in cube_dir:
                cube_dir_name = cube_dir
        # 进入当前cube路径， 读取所有.det.xml文件
        cube_path = '{}\{}'.format(path, cube_dir_name)
        files_names = win_conn.get_files('*.det.xml', cube_path)
        # 读取所有文件内容，匹配量值对应视图或表名
        content = ''
        for file_name in files_names:
            file_content = win_conn.get_file_connect(file_name, cube_path)
            content += file_content
        redis_conn.set(redis_key, content, ex=60 * 60 * 24)  # ex参数设置60s过期
    else:
        content = redis_conn.get(redis_key).decode('utf-8')
    redis_conn.close()

    # 根据规则‘<Measure>([\s\S].*?)</Measure>’匹配
    measure_pat = re.compile(r'<Measure>(.*?)</Measure>')
    measures_list = measure_pat.findall(content.replace('\r\n', ''))
    # 循环匹配出量值名与对应视图或表名
    m_name_pat = re.compile('<Name>(.*?)</Name>')
    m_view_pat = re.compile('<TableID>(.*?)</TableID>')
    result = {}
    for m_item in measures_list:
        m_name = m_name_pat.findall(m_item.replace('\r\n', ''))
        m_view_name = m_view_pat.findall(m_item.replace('\r\n', ''))
        if len(m_name) == 1 and len(m_view_name) == 1:
            # 找到当前量值
            if measure.MEASURE_NAME == m_name[0]:
                result.setdefault(m_name[0], m_view_name[0])
    return result


if __name__ == '__main__':
    from app_cube.utils.connect.my_cube import MyCube
    from app_cube.utils.connect.my_win import MyWin

    path = r'C:\Program Files\Microsoft SQL Server\MSAS11.MSSQLSERVER\OLAP\Data\YWC_SSAS.0.db'
    win_conn = MyWin('127.0.0.1', 'Administrator', 'zjs')
    conn = MyCube(location='http://127.0.0.1:8888/msmdpump.dll', username='Win10-2020YKVZB\Administrator',
                  password='zjs')
    catalog = conn.get_catalog('YWC_SSAS')
    cube = conn.get_cube(catalog.get('YWC_SSAS'), '抗菌药物分析')
    cube = list(cube.values())[-1]
    measures = conn.get_measure(cube)
    measure = list(measures[0].values())[-1]
    measure_dict = get_measure_table_or_view(cube=cube, measure=measure, win_conn=win_conn, path=path)
    print(measure_dict)
